<template>
  <view class="plan-list">
    <view class="top">
      <text class="title">计划</text>
      <text class="handle" @click="showPopup">新增</text>
    </view>

    <!-- 计划列表 -->
    <template v-if="state.dataList.length">
      <view v-for="(plan, index) in state.dataList" :key="plan.id" class="plan" :class="{
        complete: plan.isComplete,
      }">
        <!-- <view class="time-info">
          <text class="tip">{{
            isTodayPlan(plan.dueTime)
              ? "Today"
              : formatDate(new Date(plan.dueTime), "MM-dd")
          }}</text>
          <text class="time">{{
            formatDate(new Date(plan.dueTime), "hh:mm")
            }}</text>
        </view> -->

        <movable-area class="movable">
          <movable-view class="movable movable-view" :class="{
            'one-btn': plan.isComplete,
          }" direction="horizontal" inertia damping="20" out-of-bounds :x="plan.x" @touchstart="touchStart"
            @touchend="touchEnd(index, $event)">
            <view class="info" @click="hideHandle(index)">
              <image class="avatar" src="@/assets/svgs/plan.svg"></image>
              <view class="detail">
                <text class="title">{{ plan.title }}</text>
                <text class="notes">{{ plan.notes }}</text>
              </view>
              <view class="time">
                <text class="number">{{ plan.time }}</text>
                <text class="unit">min</text>
              </view>
            </view>
            <view class="handle">
              <view class="btn delete" @click="deletePlan(plan.id)">
X              </view>
              <view v-if="!plan.isComplete" style="text-align:center" class="btn done" @click="donePlan(plan.id)">
                <!--  <image class="icon" src="@/assets/svgs/done.svg"></image>             </view> -->
                  √
              </view>
            </view>
          </movable-view>
        </movable-area>
      </view>
    </template>
    <!-- 无计划时显示 -->
    <template v-else>
      <view class="empty">空空如也~</view>
    </template>

    <!-- 新增计划 -->
    <MyPopup :show="state.isShowPopup" @hide="hidePopup">
      <view class="popup">
        <view class="title">新增计划</view>
        <view class="form">
          <MyForm :model="state.newPlan" :rules="rules" ref="myForm">
            <MyFormItem label="标题" prop="title">
              <MyInput maxlength="10" @updateModelValue="updateModelValue" :modelValue="state.newPlan.title"
                obj="title" />
            </MyFormItem>
            <!-- <MyFormItem label="开始时间" prop="dueTime"> -->
            <MyFormItem label="活动类型" >
              <!-- <MyDateTimePicker v-model="state.newPlan.dueTime" time :startTime="state.startTime"
                :endTime="state.endTime">
              </MyDateTimePicker> -->
              <MyInput maxlength="10" @updateModelValue="updateModelValue" :modelValue="state.newPlan.dueTime"
                 />
            </MyFormItem>
            <!-- <MyFormItem label="用时(分钟)" prop="time"> -->
            <MyFormItem label="活动地点" >
              <MyInput maxlength="10" type="number" @updateModelValue="updateModelValue"
                :modelValue="state.newPlan.time"  />
            </MyFormItem>
            <MyFormItem label="描述">
              <MyInput maxlength="20" @updateModelValue="updateModelValue" :modelValue="state.newPlan.notes"
                obj="notes" />
            </MyFormItem>
            <button class="submit" @click="handleNewPlanSubmit">完成</button>
          </MyForm>
        </view>
      </view>
    </MyPopup>
    <MyMessage ref="myMessageRef"></MyMessage>
  </view>
</template>

<script>
// import { Plan } from "@/types/plan";
import { formatDate } from "@/utils/methods.js";
import MyPopup from '@/components/MyPopup/MyPopup.vue'
import MyForm from '@/components/MyForm/MyForm.vue'
import MyInput from '@/components/MyInput/MyInput.vue'
import MyMessage from '@/components/MyMessage/MyMessage.vue'
import MyFormItem from '@/components/MyFormItem/MyFormItem.vue'
import http from '@/api/backend'

export default {
  name: "Plan",
  props: {
    data: {
      type: Array,
      default: [],
    },
    petId:{
      type: Number,
      default:-1
    }
  },

  data() {
    return {
      myForm: null,
      initData: this.data,
      state: {
        dataList: [],
        offset: 10,
        currentTouchX: 0,
        isShowPopup: false,
        newPlan: {},
        startTime: Date.now(),
        endTime: Date.now() + 1000 * 3600 * 24 * 180,
      },
      rules: {
        title: [
          {
            required: true,
            message: "请输入标题",
          },
        ],
        dueTime: [
          {
            required: true,
            message: "请输入开始时间",
          },
        ],
        time: [
          {
            required: true,
            message: "请输入用时",
          },
        ],
      },
    };
  },
  mounted(){
    // console.log('新',this.data);
  },
  components: {
    MyPopup, MyForm, MyInput, MyMessage, MyFormItem
  },
  watch: {
    data: {
      handler(newVal) {
        
        const dataList = newVal.map((item) => {
          return { ...item, x: 0 };
        });
        const completeds = dataList.filter((item) => item.isComplete);
        const inCompleteds = dataList.filter((item) => !item.isComplete);
        completeds.sort((a, b) => Date.parse(b.dueTime) - Date.parse(a.dueTime));
        inCompleteds.sort((a, b) => Date.parse(b.dueTime) - Date.parse(a.dueTime));
        this.state.dataList = inCompleteds.concat(completeds);
        console.log(this.state.dataList);
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    touchStart(e) {
      const { clientX } = e.changedTouches[0];
      this.state.currentTouchX = clientX;
    },
    touchEnd(index, e) {
      const { clientX } = e.changedTouches[0];
      if (this.state.currentTouchX - clientX > this.state.offset) {
        this.state.dataList = this.state.dataList.map((item, i) => {
          if (i !== index) {
            item.x = 0;
          } else {
            item.x = -999;
          }
          return item;
        });
      } else if (clientX - this.state.currentTouchX > this.state.offset) {
        this.state.dataList[index].x = 0;
      }
    },
    hideHandle(index) {
      this.state.dataList[index].x = 0;
    },
    deletePlan(id) {
      this.$emit("delete", id);
    },
    donePlan(id) {
      this.$emit("done", id);
    },
    showPopup() {
      // console.log(this.state.data);
      console.log(this.petId);
      this.state.newPlan = {
        id: this.petId,
        avatar: "",
        title: "",
        time: "",
        // dueTime: formatDate(new Date(), "yyyy-MM-dd hh:mm"),
        dueTime: "",
        notes: "",
        isComplete: false,
      };
      this.state.isShowPopup = true;
    },
    hidePopup() {
      this.state.isShowPopup = false;
    },
    updateModelValue(obj, val) {
      this.state.newPlan[`${obj}`] = val
    },
    handleNewPlanSubmit() {
      // console.log(this.state.newPlan)

      // title标题 dueTime开始时间 time用时
      if (!this.state.newPlan.title || !this.state.newPlan.dueTime || !this.state.newPlan.time) {
        this.$refs.myMessageRef.show({
          type: 'error',
          message: '请输入必输项！',
        });
        return;
      }
      // console.log(this.state.newPlan)
      this.$refs.myForm.validate((valid) => {
        if (valid) {
          this.$emit("add", this.state.newPlan);
          this.hidePopup();
        }
      });
    },
    isTodayPlan(dueTime) {
      return new Date(dueTime).getDate() === new Date().getDate();
    },
  },
};
</script>

<style lang="less" scoped>
// 行为相关颜色
@my-color-primary: #aa69ff;
@my-color-error: #ff4747;

// 文字相关颜色
@my-text-color: #303330;
@my-text-color-grey: rgb(157, 155, 155);

.plan-list {
  margin: 0 1.5rem;

  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0.8rem;

    .title {
      font-weight: bold;
      font-size: 1.1rem;
    }

    .handle {
      color: @my-color-primary;
      font-size: 0.8rem;
    }
  }

  .empty {
    height: 200rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: @my-color-primary;
    opacity: 0.5;
    font-size: 25rpx;
  }

  .plan {
    display: flex;
    justify-content: space-between;
    margin-bottom: 0.5rem;

    &.complete {
      opacity: 0.5;
    }

    .movable {
      width: 99vw;
      height: 3.8rem;
      overflow: hidden;
      margin-left: 1rem;

      &.one-btn {
        width: 87vw;
      }
    }

    .movable-view {
      display: flex;
    }

    .time-info {
      display: flex;
      flex-direction: column;

      .tip {
        color: @my-text-color-grey;
        font-size: 0.8rem;
      }

      .time {
        font-weight: bold;
      }
    }

    .info {
      height: 3.8rem;
      flex: 1;
      background: #fff;
      border-radius: 1rem;
      margin-right: 0.8rem;
      padding: 0.5rem;
      box-sizing: border-box;
      display: flex;
      align-items: center;

      .avatar {
        height: 2rem;
        width: 2rem;
        border-radius: 0.6rem;
      }

      .detail {
        display: flex;
        flex-direction: column;
        flex: 1;
        margin: 0 0.8rem;

        .title {
          font-weight: bold;
        }

        .notes {
          font-size: 0.8rem;
          color: @my-text-color-grey;
        }
      }

      .time {
        display: flex;
        flex-direction: column;
        align-items: flex-end;

        .number {
          font-weight: bold;
          font-size: 1.2rem;
        }

        .unit {
          color: @my-text-color-grey;
          font-size: 0.6rem;
        }
      }
    }

    .handle {
      display: flex;
      align-items: center;

      .btn {
        width: 2.5rem;
        height: 2.5rem;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 0.8rem;
        margin-right: 0.3rem;

        .icon {
          width: 60%;
          height: 60%;
        }
      }

      .delete {
        background: @my-color-error;
      }

      .done {
        background: @my-color-primary;
      }
    }
  }
}

.popup {
  width: 60vw;

  .title {
    font-weight: bold;
    font-size: 1.2rem;
    color: @my-color-primary;
    margin-bottom: 1rem;
  }

  .submit {
    background: @my-color-primary;
    color: #fff;
    font-size: 1rem;
    border-radius: 0.8rem;
    margin-top: 2rem;

    &::after {
      border: none;
    }
  }
}
</style>